//
//  Date+Extend.swift
//  Date
//
//  Created by mini on 2025/4/28.
//

import Foundation

extension Date {
    
    // 计算两个日期之间相差的天数
    func daysDifference(to endDate: Date) -> Int? {
        // 获取当前日历系统
        var calendar = Calendar.current
        // 设置为当前时区
        calendar.timeZone = TimeZone.current
        // 获取两个日期的开始时间（0点0分0秒）
        let startOfDay1 = calendar.startOfDay(for: self)
        let startOfDay2 = calendar.startOfDay(for: endDate)
        // 计算两个日期之间的天数差
        let components = calendar.dateComponents([.day], from: startOfDay1, to: startOfDay2)
        return components.day
    }
    
    // 判断日期是否晚于今天：
    func isLaterThanToday() -> Bool {
        // 如果差值小于0，表示这个日期比今天晚（在未来）
        return self.daysDifference(to: Date())! < 0
    }
    
    var status: String {
        let calendar = Calendar.current
        if calendar.isDateInToday(self) {
            return "今天 "
        } else if calendar.isDateInYesterday(self) {
            return "昨天 "
        } else if calendar.isDateInTomorrow(self) {
            return "明天 "
        } else {
            return ""
        }
    }
    
    func weekRange() -> (start: Date, end: Date)? {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)
        guard let sunday = calendar.date(from: components) else { return nil }
        guard let saturday = calendar.date(byAdding: .day, value: 6, to: sunday) else { return nil }
        return (sunday, saturday)
    }
}
